//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by Apple on 15/11/13.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {
    
    
    //增加用户属性
    var account: UserAccount?
    //是否登录
    var userLogin: Bool{
        return account?.access_token != nil
    }
    var token: String?{
        return account?.access_token
    }
    var userName:String?{
        return account?.name
    }
    var headURL:NSURL?{
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    override init() {
        account = UserAccount.loadAccount()
    }
    
    
    //加载用户token
    func loadAccessToken(code:String, finished:(error: NSError?) ->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            /*
            9206a32ee3bd78ed7c7300a8caf265b6
            print(result)
            {
            "access_token" = "2.00OOIYRG0WHpsC7d49d8f8840YQTv5";访问令牌
            "expires_in" = 157679999;
            "remind_in" = 157679999;//过期时间
            uid = 5756129490;用户身份证明
            }
            */
            //是字典走下去
            if let dict = result as? [String:AnyObject]{
                
                let account = UserAccount(dict: dict)
//                print(account.access_token) : 2.00OOIYRG0WHpsC7d49d8f8840YQTv5
                self.loadUserInfo(account,finished: finished)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    //MARK访问获取用户数据
    private func loadUserInfo(account:UserAccount, finished:(error:NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String : AnyObject]{
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
//                print(account)
                account.saveAccount()
                finished(error: nil)
            }
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
    }
}
